<template>
  <a-layout-header
    class="header flex-r-jb"
    :style="headerStyle"
    :class="isDark ? '' : 'border-[#eee] border-b-[1px] border-solid'"
  >
    <div class="cursor-pointer side-logo" @click="$router.push('/')">
      <Transition name="slide-fade">
        <!-- v-if="!layoutState.side.collapsed" -->
        <div class="flex items-center">
          <img :src="logo" alt="" srcset="" class="w-[26px] h-[26px] mr-[5px]" :class="logoClass" />
          <div class="slide-fade-title whitespace-nowrap" :style="headerStyle">CMS 管理系统</div>
        </div>
      </Transition>
    </div>
    <div class="header-menu" style="cursor: pointer" :style="headerStyle">
      <a-tooltip placement="bottom" color="#fff">
        <template #title>
          <span style="color: #5e5e5e">清除缓存</span>
        </template>
        <i
          class="iconfont icon-qingchuhuancun mr-0 text-[18px] h-[20px] leading-[20px]"
          @click="clearCache"
          :style="headerStyle"
        />
      </a-tooltip>
      <a-divider type="vertical" />
      <a-popover
        :visible="popoverVisible"
        overlayClassName="header-popover"
        placement="bottomRight"
        autoAdjustOverflow
        :style="headerStyle"
        @visibleChange="visibleChange"
      >
        <template #content style="cursor: pointer" :style="headerStyle">
          <div>
            <p @click="handleClick(1)">个人信息</p>
          </div>
          <div>
            <p @click="handleClick(2)">登录记录</p>
          </div>
          <div @click="handleClick(3)">
            <p>偏好设置</p>
          </div>
          <div @click="editPwd">
            <p>修改密码</p>
          </div>
          <div @click="logOut">
            <p>退出登录</p>
          </div>
        </template>
        <a-avatar :src="isDark ? moren : avatar" :size="24" class="text-[#A7AECE]" :style="headerStyle"></a-avatar>
        <span class="header-menu-username" :style="headerStyle">{{ user.user.user_name || '请登录' }}</span>
        <down-outlined style="color: #fff" :style="headerStyle" />
      </a-popover>
    </div>
    <a-drawer
      :width="getWidth"
      class="drawer-box z-[9999]"
      :closable="false"
      placement="right"
      v-model:visible="drawerVisible"
    >
      <div class="drawer-box-title">
        <span>{{ geTitle }}</span>
        <div class="drawer-box-title-background" @click="closeDrawer">
          <close-outlined />
        </div>
      </div>
      <div class="drawer-box-personal" v-if="isPersonal === 1">
        <div class="drawer-box-personal-avatar">
          <div class="drawer-box-personal-avatar-image">
            <img :src="avatar" alt="" />
          </div>
          <div class="drawer-box-personal-avatar-name">{{ user.user.user_name }}</div>
        </div>
        <div class="drawer-box-personal-info">
          <div class="drawer-box-personal-info-label">角色</div>
          <div class="drawer-box-personal-info-value">{{ user.user.role }}</div>
        </div>
        <div class="drawer-box-personal-info">
          <div class="drawer-box-personal-info-label">创建时间</div>
          <div class="drawer-box-personal-info-value">{{ formatToDateTime(+user.user.created_at * 1000) }}</div>
        </div>
        <div class="drawer-box-personal-info">
          <div class="drawer-box-personal-info-label">最近登录</div>
          <div class="drawer-box-personal-info-value">{{ formatToDateTime(+user.user.login_time * 1000) }}</div>
        </div>
      </div>
      <div class="drawer-box-table" v-else-if="isPersonal === 2">
        <LoginRecord />
      </div>
      <div v-else>
        <a-descriptions title="" :column="5">
          <a-descriptions-item v-for="theme in themeStyle" :key="theme.value">
            <a-tooltip :title="theme.label">
              <div
                class="style-checbox-item"
                :class="{ active: themeStore.navTheme === theme.value }"
                @click="setNavTheme(theme.value)"
              >
                <svg-icon :name="theme.value" size="62" class="cursor-pointer"></svg-icon>
              </div>
              <div>{{ theme.label }}</div>
            </a-tooltip>
          </a-descriptions-item>
        </a-descriptions>
        <!--  <a-descriptions title="主题色" :column="9">
          <a-descriptions-item v-for="item in themeColors" :key="item.key">
            <div class="style-checbox-item">
              <a-tooltip :title="item.title">
                <a-tag :color="item.value" @click="setThemeColor({ primaryColor: item.value })">
                  <span :style="{ visibility: getThemeColorVisible(item.value) }"> ✔ </span>
                </a-tag>
              </a-tooltip>
            </div>
          </a-descriptions-item>
          <a-descriptions-item key="custom">
            <div class="style-checbox-item">
              <a-tooltip title="自定义">
                <a-tag :color="customColor" class="relative overflow-hidden">
                  <input
                    v-model="customColor"
                    type="color"
                    class="absolute inset-0"
                    :style="colorPickerStyle"
                    @input="setThemeColor({ primaryColor: customColor })"
                  />
                  <span :style="{ visibility: getThemeColorVisible(customColor) }"> ✔ </span>
                </a-tag>
              </a-tooltip>
            </div>
          </a-descriptions-item>
        </a-descriptions> -->
      </div>
    </a-drawer>
  </a-layout-header>
  <modal-view
    title="修改密码"
    v-model:visible="pwdVisible"
    okText="确定"
    cancelText="取消"
    :width="430"
    :afterClose="() => editFormRef.resetFields()"
    @confirm="pwdFormConfirm"
    @cancel="pwdFormCancel"
  >
    <a-form
      ref="editFormRef"
      :model="pwdFormState"
      :rules="pwdFormRules"
      :labelCol="{ style: { width: '110px' } }"
      labelAlign="left"
      :colon="false"
    >
      <a-form-item label="原密码" name="old_password">
        <a-input-password v-model:value.trim="pwdFormState.old_password" class="w-[240px]" placeholder="请输入原密码" />
      </a-form-item>
      <a-form-item label="新密码" name="new_password">
        <a-input-password v-model:value.trim="pwdFormState.new_password" class="w-[240px]" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item label="确认新密码" name="affirm_password">
        <a-input-password
          v-model:value.trim="pwdFormState.affirm_password"
          class="w-[240px]"
          placeholder="请再次输入新密码"
        />
      </a-form-item>
    </a-form>
  </modal-view>
  <!-- 清除缓存对话框 -->
  <modal-view
    title="提示"
    v-model:visible="clearVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="clearConfirm"
    @cancel="clearCancel"
  >
    <span>确定要清除缓存吗</span>
  </modal-view>
</template>

<script setup lang="ts">
import { computed, ref, type StyleValue, type PropType, type CSSProperties } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ModalView from '@/components/components/modal/ModalView.vue'
import useStore from '@/stores'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import LoginRecord from './LoginRecord.vue'
import { message, Modal, type MenuTheme } from 'ant-design-vue'
import { createVNode } from 'vue'
import { layoutState } from '../../state'
import { managerState, pwdFormState, pwdFormRules } from '@/views/modules/permission/manager-list/state'
import apis from '@/apis'
import { formatToDateTime } from '@/utils/format'
import { storage } from '@/utils/storage'
import moren from '@/assets/icon/moren.png'
import defaultLogo from '@/assets/logo.svg'
import avatar from '@/assets/icon/avatar.png'
import { layouts, themeColors, themeStyle } from './constant'
import type { ThemeName, Theme, ThemeState } from '@/stores/modules/projectConfig'
import { useThemeStore } from '@/stores/modules/projectConfig'
import defaultIcon from '@/assets/logo.svg'
defineProps({
  theme: {
    type: String as PropType<MenuTheme>
  },
  collapsed: {
    type: Boolean
  }
})
const { user } = useStore()
const {
  permission: { updatePwd }
} = apis
const adminId = storage.get('user').user.admin_id
const drawerVisible = ref(false)
const popoverVisible = ref()
const pwdVisible = ref(false)
const clearVisible = ref(false)
const router = useRouter()
const route = useRoute()
const editFormRef = ref()
const isPersonal = ref(1)
const themeStore = useThemeStore()
const isDark = ref(false)
const headerStyle = computed<CSSProperties>(() => {
  const { navTheme, layout } = themeStore
  isDark.value = navTheme === 'dark'
  console.log('navTheme: ', navTheme)
  return {
    backgroundColor: isDark.value ? '' : 'rgba(255, 255, 255, 0.85)',
    color: isDark.value ? 'rgba(255, 255, 255, 0.85)' : '#262626'
  }
})
// const customColor = ref(themeStore.primaryColor)
// const colorPickerStyle = computed(() => ({ '--custom-color': customColor.value } as StyleValue))
const setNavTheme = (theme: ThemeName) => {
  themeStore.setTheme({ navTheme: theme })
}
// const setLayout = (layout: ThemeState['layout']) => {
//   themeStore.setTheme({ layout })
// }
// const setThemeColor = ({ primaryColor }: Theme) => {
//   themeStore.fillColor({ primaryColor })
// }
const getThemeColorVisible = (color: string) => (themeStore.primaryColor === color ? 'visible' : 'hidden')

//退出登录
const logOut = () => {
  popoverVisible.value = false
  Modal.confirm({
    title: '确定退出系统吗?',
    okText: '确定',
    cancelText: '取消',
    icon: createVNode(ExclamationCircleOutlined),
    onOk() {
      return new Promise((resolve, reject) => {
        user.logout().then(() => {
          user.resetToken()
          router.push(`/sign-in?redirect=${route.fullPath}`)
          resolve(null)
        })
      }).catch(() => console.log('Oops errors!'))
    },
    onCancel() {}
  })
}
//清除缓存
const clearCache = () => {
  clearVisible.value = true
}
/**
  清除缓存对话框事件
 */
const clearConfirm = (value: any) => {
  console.log('value: ', value)
  // atlas_del_classify({ categ_id: [categ_id.value] }).then(() => {
  setTimeout(() => {
    message.success('清除成功')
    clearVisible.value = value
  }, 500)
  // })
}
const clearCancel = () => {
  clearVisible.value = false
}
const visibleChange = (visible: boolean) => {
  popoverVisible.value = visible
}
const handleClick = (state: number) => {
  isPersonal.value = state
  drawerVisible.value = true
  popoverVisible.value = false
}
const closeDrawer = () => {
  drawerVisible.value = false
}
//修改密码
const editPwd = () => {
  pwdVisible.value = true
  popoverVisible.value = false
}
/**
 修改密码对话框事件
 */
const pwdFormConfirm = (value: any) => {
  console.log('value: ', value)
  editFormRef.value.validate().then(() => {
    //请求
    pwdFormState.admin_id = adminId
    updatePwd(pwdFormState).then((res: any) => {
      message.success('密码重置成功,请重新登录')
      pwdVisible.value = value
      editFormRef.value.resetFields()
      router.push('/sign-in')
    })
  })
}
const pwdFormCancel = () => {
  pwdVisible.value = false
}
const getWidth = computed(() => {
  return isPersonal.value === 1 ? '380' : isPersonal.value === 2 ? '914' : '406'
})
const geTitle = computed(() => {
  return isPersonal.value === 1 ? '个人信息' : isPersonal.value === 2 ? '登录记录' : '偏好设置'
})
const logo = computed(() => {
  console.log('user.logoConfig.logo: ', user.logoConfig.logo)
  if (user.logoConfig.logo) {
    const res = user.logoConfig.status === 1 ? user.logoConfig.logo : defaultLogo
    return res
  }
  return defaultLogo
})

const logoClass = computed(() => {
  const classMaps: Record<number, any> = {
    1: 'square',
    2: 'circle',
    3: 'rectangle'
  }
  return classMaps[user.logoConfig?.logo_shape ?? 1]
})
</script>

<style lang="less">
.style-checbox-item {
  position: relative;
  cursor: pointer;

  &.active:after {
    content: '✔';
    position: absolute;
    bottom: 20px;
    right: 12px;
    color: #0083ff;
  }
}
.header-popover {
  width: 160px;
  top: 40px !important;

  :deep {
    .ant-popover-inner {
      width: 160px;
    }
  }

  .ant-popover-inner-content {
    padding: 12px 24px;
    color: rgba(0, 0, 0, 0.85);

    div:last-child {
      border-top: 1px solid #e8e8e8;
    }

    div {
      cursor: pointer;
      height: 40px;
      line-height: 40px;

      p {
        margin: 0;
      }
    }
  }
}
.ant-drawer-body {
  padding: 24px 24px 0;
}
</style>
<style scoped lang="less">
.drawer-box {
  :deep(.ant-drawer-body) {
    padding: 41px 40px;
    box-sizing: border-box;
  }

  &-title {
    display: flex;
    justify-content: space-between;

    span {
      font-size: 20px;
      color: #262626;
      font-weight: 500;
    }

    &-background {
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 45px;
      border-radius: 50%;
      background-color: #f4f5f9;
      cursor: pointer;
    }
  }

  &-personal {
    &-avatar {
      height: 120px;
      display: flex;
      align-items: center;
      padding: 20px 40px;
      box-sizing: border-box;
      background: #fafafa;
      border-radius: 8px;
      margin-top: 41px;

      &-image {
        width: 80px;

        img {
          width: 100%;
          border-radius: 50%;
        }
      }

      &-name {
        font-size: 16px;
        color: #262626;
        margin-left: 16px;
      }
    }

    &-info {
      font-size: 14px;
      margin-top: 40px;

      &-label {
        color: #8c8c8c;
      }

      &-value {
        color: #262626;
        margin-top: 7px;
      }
    }
  }

  &-table {
    margin-top: 24px;
  }
}

.header {
  height: 56px;
  // background: #0865cf;
  background: @primary-color;
  padding: 0 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.ant-divider-horizontal {
  margin: 10px 0;
}

.ant-layout-header {
  :deep(.ant-menu-item) {
    padding: 0 30px;
  }
}

.slide-fade-enter-active {
  transition: all 1s ease-out;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}

.slide-fade-title {
  width: 133px;
  height: 26px;
  line-height: 26px;
  font-size: 20px;
  color: #ffffff;
  letter-spacing: 1.6px;
  font-weight: 500;
}

:deep(.ant-divider-vertical) {
  border-right: 1px solid #fff;
  margin: 0 24px;
  height: 19px;
}

:deep(.a-avatar) {
  border-radius: 50%;
}

.header-menu {
  height: 100%;
  display: flex;
  align-items: center;

  &-username {
    margin: 0 16px;
    color: #fff;
    align-items: center;
  }
}
</style>
